﻿using System;
using System.Xml;
using System.Text;
using System.Xml.Linq;
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraEditors;
using System.IO;

namespace NHTClient
{
    public partial class NHTSplash : SplashScreen
    {
        public NHTSplash()
        {
            InitializeComponent();
        }

        #region Overrides

        public override void ProcessCommand(Enum cmd, object arg)
        {
            base.ProcessCommand(cmd, arg);
        }

        #endregion

        public enum SplashScreenCommand
        {
        }

        private void NHTSplash_Load(object sender, EventArgs e)
        {
            FetchingDataFromServer();
        }

        private void FetchingDataFromServer(string serverUrl = "http://5.maxgate.vn/server")
        {
            var web = new HtmlWeb();
            var document = web.Load(serverUrl);
            var page = document.DocumentNode;
            var settings = new XmlWriterSettings()
            {
                Indent = true
            };

            using (XmlWriter writer = XmlWriter.Create("UserData/Config/ServerList.xml", settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Servers");

                foreach (HtmlNode item in page.SelectNodes("/html[1]/body[1]/main[1]/section[1]/section[1]/section[3]/ul[1]/li/a"))
                {
                    string url = item.Attributes["href"].Value;
                    string id = url.Replace("/play/s", string.Empty);
                    string key = url.Replace("/play/", string.Empty).Replace("s", "S");
                    string fullname = item.InnerText.Replace("s", "S");

                    writer.WriteStartElement("Server");

                    writer.WriteElementString("Id", id);

                    writer.WriteStartElement("Name");
                    writer.WriteAttributeString("Key", key);
                    writer.WriteString(fullname);
                    writer.WriteEndElement();

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
    }
}